<template>
  <div class="merchant-qualification">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商家资质审核管理</span>
          <el-button-group>
            <el-button type="primary" @click="handleBatchAudit"
              >批量审核</el-button
            >
            <el-button type="success" @click="exportData">导出数据</el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家名称">
          <el-input
            v-model="searchForm.merchantName"
            placeholder="请输入商家名称"
          />
        </el-form-item>
        <el-form-item label="商家类型">
          <el-select
            v-model="searchForm.merchantType"
            placeholder="请选择商家类型"
          >
            <el-option label="餐饮美食" value="food" />
            <el-option label="零售商店" value="retail" />
            <el-option label="生活服务" value="service" />
            <el-option label="文化娱乐" value="entertainment" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="资质类型">
          <el-select
            v-model="searchForm.qualificationType"
            placeholder="请选择资质类型"
          >
            <el-option label="营业执照" value="business_license" />
            <el-option label="食品经营许可" value="food_license" />
            <el-option label="卫生许可" value="health_permit" />
            <el-option label="特种行业许可" value="special_permit" />
            <el-option label="商标注册" value="trademark" />
            <el-option label="其他证照" value="other_license" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.status" placeholder="请选择审核状态">
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="sortedQualificationList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          prop="id"
          label="审核ID"
          width="100"
          sortable="custom"
        />
        <el-table-column
          prop="merchantName"
          label="商家名称"
          min-width="180"
          sortable="custom"
        />
        <el-table-column prop="merchantType" label="商家类型" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{
              getMerchantTypeLabel(row.merchantType)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="qualificationType"
          label="资质类型"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag>{{
              getQualificationTypeLabel(row.qualificationType)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="submitTime"
          label="提交时间"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="expiryDate"
          label="有效期至"
          width="160"
          sortable="custom"
        />
        <el-table-column
          prop="status"
          label="审核状态"
          width="100"
          sortable="custom"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                v-if="row.status === 'pending'"
                type="primary"
                size="small"
                @click="handleAudit(row)"
              >
                审核
              </el-button>
              <el-button
                v-if="row.status === 'approved'"
                type="danger"
                size="small"
                @click="handleRevoke(row)"
              >
                吊销
              </el-button>
              <el-button
                v-if="row.status === 'revoked'"
                type="primary"
                size="small"
                @click="handleReaudit(row)"
              >
                重新审核
              </el-button>
              <el-button type="info" size="small" @click="viewDetail(row)">
                详情
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
        
        <!-- 空状态模板 -->
        <template #empty>
          <el-empty 
            description="暂无资质审核数据" 
            :image-size="200"
          >
            <el-button type="primary" @click="fetchQualificationList">刷新数据</el-button>
          </el-empty>
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      title="资质审核"
      width="500px"
      class="qualification-dialog"
      :append-to-body="true"
      :lock-scroll="true"
      destroy-on-close
    >
      <el-scrollbar height="400px">
        <el-form :model="auditForm" label-width="100px">
          <el-form-item label="审核结果" required>
            <el-radio-group v-model="auditForm.result">
              <el-radio label="approved">通过</el-radio>
              <el-radio label="rejected">驳回</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="auditForm.result === 'approved'"
            label="有效期至"
            required
          >
            <el-date-picker
              v-model="auditForm.expiryDate"
              type="date"
              placeholder="选择有效期"
              :disabled-date="(time) => time.getTime() < Date.now()"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="审核说明">
            <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="4"
              placeholder="请输入审核说明"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAudit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="资质详情"
      width="800px"
      :append-to-body="true"
      :lock-scroll="true"
      destroy-on-close
      class="qualification-dialog"
    >
      <el-scrollbar height="calc(90vh - 200px)">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="审核ID">{{
            currentQualification.id
          }}</el-descriptions-item>
          <el-descriptions-item label="商家名称">{{
            currentQualification.merchantName
          }}</el-descriptions-item>
          <el-descriptions-item label="商家类型">
            <el-tag size="small">{{
              getMerchantTypeLabel(currentQualification.merchantType)
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="资质类型">
            <el-tag>{{
              getQualificationTypeLabel(currentQualification.qualificationType)
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="证件号码">{{
            currentQualification.licenseNumber
          }}</el-descriptions-item>
          <el-descriptions-item label="法定代表人">{{
            currentQualification.legalPerson
          }}</el-descriptions-item>
          <el-descriptions-item label="注册地址">{{
            currentQualification.registeredAddress
          }}</el-descriptions-item>
          <el-descriptions-item label="经营范围" :span="2">{{
            currentQualification.businessScope
          }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{
            currentQualification.submitTime
          }}</el-descriptions-item>
          <el-descriptions-item label="有效期至">{{
            currentQualification.expiryDate
          }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getStatusTag(currentQualification.status)">
              {{ getStatusLabel(currentQualification.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="资质文件" :span="2">
            <div class="qualification-files">
              <el-image
                v-for="(url, index) in currentQualification.files"
                :key="index"
                :src="url"
                :preview-src-list="currentQualification.files"
                fit="contain"
                class="preview-image"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentQualification.status !== 'pending'"
            label="审核信息"
            :span="2"
          >
            <div>审核人：{{ currentQualification.auditor }}</div>
            <div>审核时间：{{ currentQualification.auditTime }}</div>
            <div>审核说明：{{ currentQualification.auditComment }}</div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentQualification.status === 'revoked'"
            label="吊销信息"
            :span="2"
          >
            <div>吊销人：{{ currentQualification.revokeBy }}</div>
            <div>吊销时间：{{ currentQualification.revokeTime }}</div>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="currentQualification.reauditTime"
            label="重审信息"
            :span="2"
          >
            <div>重审提交人：{{ currentQualification.reauditBy }}</div>
            <div>重审提交时间：{{ currentQualification.reauditTime }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// 搜索表单
const searchForm = reactive({
  merchantName: "",
  merchantType: "",
  qualificationType: "",
  status: "",
  dateRange: [],
});

// 表格数据
const loading = ref(false);
const qualificationList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedQualifications = ref([]);

// 审核对话框
const auditDialogVisible = ref(false);
const auditForm = reactive({
  result: "",
  expiryDate: "",
  comment: "",
});

// 详情对话框
const detailDialogVisible = ref(false);
const currentQualification = ref({});

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取商家类型标签
const getMerchantTypeLabel = (type) => {
  const types = {
    food: "餐饮美食",
    retail: "零售商店",
    service: "生活服务",
    entertainment: "文化娱乐",
    other: "其他",
  };
  return types[type] || type;
};

// 获取资质类型标签
const getQualificationTypeLabel = (type) => {
  const types = {
    business_license: "营业执照",
    food_license: "食品经营许可",
    health_permit: "卫生许可",
    special_permit: "特种行业许可",
    trademark: "商标注册",
    other_license: "其他证照",
  };
  return types[type] || type;
};

// 获取状态标签
const getStatusLabel = (status) => {
  const statuses = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已驳回",
    expired: "已过期",
    revoked: "已吊销",
  };
  return statuses[status] || status;
};

// 获取状态标签样式
const getStatusTag = (status) => {
  const statuses = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
    expired: "info",
    revoked: "danger",
  };
  return statuses[status] || "";
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchQualificationList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.dateRange = [];
  handleSearch();
};

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedQualifications.value = val;
};

// 获取资质列表
const fetchQualificationList = async () => {
  loading.value = true;
  
  try {
    // 构建查询参数
    const params = {};
    if (searchForm.merchantName) params.merchantName = searchForm.merchantName;
    if (searchForm.merchantType) params.merchantType = searchForm.merchantType;
    if (searchForm.qualificationType) params.qualificationType = searchForm.qualificationType;
    if (searchForm.status) params.status = searchForm.status;
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }
    params.page = currentPage.value;
    params.size = pageSize.value;
    
    const response = await service.get('/admin/merchants/qualifications', { params });
    
    if (response.code === 200) {
      qualificationList.value = response.data.list || [];
      total.value = response.data.total || 0;
    } else {
      // 使用测试数据
      // 已在脚本中设置的mockData
      total.value = mockData.length;
    }
  } catch (error) {
    console.error("获取资质列表失败：", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchQualificationList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchQualificationList();
};

// 审核单个资质
const handleAudit = (row) => {
  currentQualification.value = row;
  auditForm.result = "";
  auditForm.expiryDate = "";
  auditForm.comment = "";
  auditDialogVisible.value = true;
};

// 查看详情
const viewDetail = (row) => {
  currentQualification.value = row;
  detailDialogVisible.value = true;
};

// 处理吊销
const handleRevoke = (row) => {
  ElMessageBox.confirm(
    "确定要吊销该商家的资质吗？吊销后商家将无法继续经营。",
    "吊销确认",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    },
  )
    .then(async () => {
      try {
        loading.value = true;
        
        const response = await service.post(`/admin/merchants/qualifications/${row.id}/revoke`);
        
        if (response.code === 200) {
          // 更新当前记录状态
          const index = qualificationList.value.findIndex(item => item.id === row.id);
          if (index !== -1) {
            qualificationList.value[index] = {
              ...qualificationList.value[index],
              status: "revoked",
              revokeTime: new Date().toLocaleString(),
              revokeBy: "当前管理员",
            };
          }
          
          ElMessage.success("资质已吊销");
        } else {
          ElMessage.error(response.message || "吊销失败");
        }
      } catch (error) {
        console.error("吊销失败：", error);
        ElMessage.error("吊销失败");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 处理重新审核
const handleReaudit = (row) => {
  ElMessageBox.confirm("确定要重新审核该商家的资质吗？", "重新审核确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  })
    .then(async () => {
      try {
        loading.value = true;
        
        const response = await service.post(`/admin/merchants/qualifications/${row.id}/reaudit`);
        
        if (response.code === 200) {
          // 更新当前记录状态
          const index = qualificationList.value.findIndex(item => item.id === row.id);
          if (index !== -1) {
            qualificationList.value[index] = {
              ...qualificationList.value[index],
              status: "pending",
              reauditTime: new Date().toLocaleString(),
              reauditBy: "当前管理员",
              // 清除之前的审核信息
              expiryDate: null,
              auditComment: null,
              auditor: null,
              auditTime: null,
            };
          }
          
          ElMessage.success("已重置为待审核状态");
        } else {
          ElMessage.error(response.message || "操作失败");
        }
      } catch (error) {
        console.error("重新审核失败：", error);
        ElMessage.error("操作失败");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 提交审核
const submitAudit = async () => {
  if (!auditForm.result) {
    ElMessage.warning("请选择审核结果");
    return;
  }

  if (auditForm.result === "approved" && !auditForm.expiryDate) {
    ElMessage.warning("请选择有效期");
    return;
  }

  try {
    loading.value = true;
    
    const response = await service.post(`/admin/merchants/qualifications/${currentQualification.value.id}/audit`, {
      result: auditForm.result,
      expiryDate: auditForm.expiryDate,
      comment: auditForm.comment
    });
    
    if (response.code === 200) {
      // 更新当前记录状态
      const index = qualificationList.value.findIndex(item => item.id === currentQualification.value.id);
      if (index !== -1) {
        qualificationList.value[index] = {
          ...qualificationList.value[index],
          status: auditForm.result,
          expiryDate: auditForm.expiryDate,
          auditComment: auditForm.comment,
          auditor: "当前审核员",
          auditTime: new Date().toLocaleString(),
        };
      }
      
      ElMessage.success("审核提交成功");
      auditDialogVisible.value = false;
      // 重置表单
      auditForm.result = "";
      auditForm.expiryDate = "";
      auditForm.comment = "";
    } else {
      ElMessage.error(response.message || "提交失败");
    }
  } catch (error) {
    console.error("提交审核失败：", error);
    ElMessage.error("提交失败");
  } finally {
    loading.value = false;
  }
};

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
};

// 获取排序后的数据
const sortedQualificationList = computed(() => {
  const list = [...qualificationList.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理特殊字段的排序
    if (sortConfig.prop === "qualificationType") {
      aValue = getQualificationTypeLabel(aValue);
      bValue = getQualificationTypeLabel(bValue);
    } else if (sortConfig.prop === "status") {
      aValue = getStatusLabel(aValue);
      bValue = getStatusLabel(bValue);
    } else if (
      sortConfig.prop === "submitTime" ||
      sortConfig.prop === "expiryDate"
    ) {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 导出数据
const exportData = () => {
  try {
    // 创建工作簿
    const wb = XLSX.utils.book_new();
    
    // 准备导出数据
    const exportData = qualificationList.value.map(item => ({
      '审核ID': item.id,
      '商家名称': item.merchantName,
      '商家类型': getMerchantTypeLabel(item.merchantType),
      '资质类型': getQualificationTypeLabel(item.qualificationType),
      '证件号码': item.licenseNumber,
      '法定代表人': item.legalPerson,
      '提交时间': item.submitTime,
      '有效期至': item.expiryDate || '-',
      '审核状态': getStatusLabel(item.status),
      '审核人': item.auditor || '-',
      '审核时间': item.auditTime || '-',
      '审核说明': item.auditComment || '-'
    }));
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(exportData);
    
    // 设置列宽
    const colWidths = [
      { wch: 15 }, // 审核ID
      { wch: 20 }, // 商家名称
      { wch: 10 }, // 商家类型
      { wch: 15 }, // 资质类型
      { wch: 20 }, // 证件号码
      { wch: 15 }, // 法定代表人
      { wch: 20 }, // 提交时间
      { wch: 15 }, // 有效期至
      { wch: 10 }, // 审核状态
      { wch: 15 }, // 审核人
      { wch: 20 }, // 审核时间
      { wch: 30 }  // 审核说明
    ];
    ws['!cols'] = colWidths;
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, "商家资质审核");
    
    // 导出Excel
    XLSX.writeFile(wb, `商家资质审核数据_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败");
  }
};

// 批量审核
const handleBatchAudit = () => {
  if (selectedQualifications.value.length === 0) {
    ElMessage.warning("请选择要审核的资质");
    return;
  }
  
  ElMessageBox.prompt("请输入批量审核的有效期(格式：YYYY-MM-DD)", "批量审核", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^\d{4}-\d{2}-\d{2}$/,
    inputErrorMessage: "日期格式不正确"
  }).then(({ value }) => {
    ElMessageBox.confirm(`确定要批量通过审核选中的${selectedQualifications.value.length}条资质记录吗？`, "批量审核确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(async () => {
      try {
        loading.value = true;
        
        const ids = selectedQualifications.value.map(item => item.id);
        const response = await service.post('/admin/merchants/qualifications/batch-audit', {
          ids: ids,
          result: 'approved',
          expiryDate: value,
          comment: '批量审核通过'
        });
        
        if (response.code === 200) {
          ElMessage.success("批量审核成功");
          fetchQualificationList();
        } else {
          ElMessage.error(response.message || "批量审核失败");
        }
      } catch (error) {
        console.error("批量审核失败：", error);
        ElMessage.error("批量审核失败");
      } finally {
        loading.value = false;
      }
    }).catch(() => {
      // 取消操作
    });
  }).catch(() => {
    // 取消操作
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchQualificationList();
});
</script>

<style scoped>
.merchant-qualification {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.qualification-dialog :deep(.el-dialog__body) {
  padding: 0;
}

.qualification-dialog .el-scrollbar {
  padding: 20px;
}

.qualification-files {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  cursor: pointer;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
